package com.zxj.system.service.user.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.zxj.common.core.domain.vo.PageVO;
import com.zxj.common.core.enums.ResultCode;
import com.zxj.common.security.exception.ServiceException;
import com.zxj.system.domain.exam.vo.ExamVO;
import com.zxj.system.domain.user.dto.UserDTO;
import com.zxj.system.domain.user.dto.UserQueryDTO;
import com.zxj.system.domain.user.vo.UserVO;
import com.zxj.system.manager.UserCacheManager;
import com.zxj.system.mapper.user.UserMapper;
import com.zxj.system.service.user.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.zxj.system.domain.user.entity.User;

import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author zxj2022
 * @since 2025-01-01
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    private final UserCacheManager userCacheManager;


    /**
     * 分页查询用户信息
     *
     * @param userQueryDTO 用户查询 DTO
     * @return 用户信息分页 VO
     */
    @Override
    public PageVO<UserVO> pageQuery(UserQueryDTO userQueryDTO) {
        PageHelper.startPage(userQueryDTO.getPageNo(), userQueryDTO.getPageSize());
        List<UserVO> examVOList = this.baseMapper.selectUserList(userQueryDTO);
        return PageVO.of(examVOList);
    }

    /**
     * 更新用户状态 - 拉黑：限制用户操作   解禁：放开对于用户限制
     * @param userDTO 用户 DTO
     * @return 更新结果
     */
    @Override
    public boolean updateStatus(UserDTO userDTO) {
        User user = this.baseMapper.selectById(userDTO.getUserId());
        if (user == null) {
            throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        user.setStatus(userDTO.getStatus());
        // 更新用户状态
        boolean flag = this.updateById(user);
        if (!flag) {
            throw new ServiceException(ResultCode.ERROR);
        }
        // 更新缓存中用户状态
        userCacheManager.updateStatus(userDTO.getUserId(), userDTO.getStatus());
        return true;
    }
}
